package controller;

import core.Model;
import core.net.XmlParser;
import gui.Frame;

import java.io.IOException;

/**
 * This class is used to allow for continuous update of model as well as GUI. It will, at a specified interval update the model with new data from webresources 
 * and call for a GUI update with the new data. This is achieved with the use of an internal <code>Thread</code> object.
 */
class UpdateThread implements Runnable{
	
	private final Frame frame;
	private Thread thread;
	private boolean running = false;
	private final long sleepDuration = 1000;

	UpdateThread(Frame f){
		frame = f;
	}
	
	/**
	 * Starts the internal thread.
	 */
	synchronized void start() {
		running = true;
		thread = new Thread(this, "Parsing&Updating");
		thread.start();
	}
	
	/**
	 * Stops the internal thread.
	 */
	synchronized void stop(){
		System.out.println("stopped");
		running = false;
		thread.interrupt();
	}

	@Override
	public void run() {
		Model model = Model.getInstance();
		while (running){
			try {
				model.replaceData(XmlParser.readDocument());
				frame.update();
				System.out.println("thread sleeping");
				Thread.sleep(sleepDuration);
			} catch (IOException e) {
				//IOException is thrown from XmlParser if connection fails.
				running = false;
				Controller.getInstance().connectionFailed();
			} catch (InterruptedException e) {
				System.out.println("InterruptedException caught. Does this break things?");
			}
		}
	}

}
